package com.sgb.kjwl.view.ui.activity.supplier3;

import android.Manifest;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.EditorInfo;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.Marker;
import com.apeng.permissions.EsayPermissions;
import com.apeng.permissions.OnPermission;
import com.chuanglan.shanyan_sdk.OneKeyLoginManager;
import com.chuanglan.shanyan_sdk.listener.OpenLoginAuthListener;
import com.google.android.material.tabs.TabLayout;
import com.green.hand.mylibrary.SoftKeyBoardListener;
import com.im.immodel.IMUtils;
import com.sgb.alimaplibrary.MapMarkerTools;
import com.sgb.alimaplibrary.SelectAddressActivity;
import com.sgb.goods.entity.ConcreteEntity;
import com.sgb.goods.entity.GoodsAttrEntity;
import com.sgb.goods.entity.GoodsItemEntity;
import com.sgb.goods.entity.inquiry.InquiryDetailsEntity;
import com.sgb.goods.utils.Constants;
import com.sgb.goods.view.activity.inquiry.InquiryPublishingActivity;
import com.sgb.goods.view.activity.inquiry.NewPurchasesActivity;
import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.GsonManager;
import com.sgb.kjwl.databinding.ActivitySupplier4Binding;
import com.sgb.kjwl.di.home.DaggerHomeFragComponent;
import com.sgb.kjwl.di.home.HomeFragModule;
import com.sgb.kjwl.model.EnquiryImAlternateEntity;
import com.sgb.kjwl.model.entity.CallPhoneEntity;
import com.sgb.kjwl.model.entity.CompanyDetailsEntity;
import com.sgb.kjwl.model.entity.GoodsSkuDetailEntity;
import com.sgb.kjwl.model.entity.ShoppingCarRequest;
import com.sgb.kjwl.model.entity.manage.WebsiteInfoEntity;
import com.sgb.kjwl.model.entity.request.MaterialFilterJson;
import com.sgb.kjwl.model.entity.shopping.ShoppingCarResponse;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.sgb.kjwl.model.entity.user.GoodsListEntity;
import com.sgb.kjwl.model.entity.user.OneKeyLoginEntity;
import com.sgb.kjwl.model.entity.user.SkuItemAttrEntity;
import com.sgb.kjwl.utils.ConfigUtils;
import com.sgb.kjwl.utils.LocationUtil;
import com.sgb.kjwl.view.ui.activity.ShoppingCar.StatementActivity;
import com.sgb.kjwl.view.ui.activity.material.ConcreteDetailActivity2;
import com.sgb.kjwl.view.ui.activity.self.JoinCompanyActivity;
import com.sgb.kjwl.view.ui.activity.self.authentication.AuthActivity3;
import com.sgb.kjwl.view.ui.activity.self.shop.ShopGoodsDetailActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.RegisterActivity3;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.adapter.search.MaterialAdapter;
import com.sgb.kjwl.view.widget.CallPhonePopWindow;
import com.sgb.kjwl.view.widget.EnterprisePopWindow;
import com.sgb.kjwl.view.widget.EnterprisePopWindowGoods;
import com.sgb.kjwl.view.widget.ThreeButtonDialog;
import com.sgb.kjwl.viewmodel.supplier3.GoodsMapFragmentModel;
import com.sgb.member.entity.QualityMemberBean;
import com.sgb.member.ui.activity.MemberApplyJoinActivity;
import com.sgb.member.ui.activity.MemberInviteJoinActivity;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.base.model.entity.SelectPopEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.RoundCornerDialog;
import com.swgk.core.event.EventConstant;
import com.swgk.core.mmkvutil.CacheMarker;
import com.swgk.core.mmkvutil.DatalUtils;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.ACAdminDialogUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PickSelectEntity;
import com.swgk.core.util.ResolutionUtil;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.util.StringUtil;
import com.swgk.core.util.UserOperating;
import com.swgk.core.view.entity.GoodsPublishEntity;
import com.swgk.core.view.entity.MenuEntity;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

import javax.inject.Inject;

import static com.swgk.core.util.ACAdminDialogUtils.MK_OURINQUIRYPRICELIST;

/**
 * @author Administrator
 */
public class NewGoodsMapFragment extends AppFragment {

    public static final String TYPE_LIST = "列表";
    public static final String TYPE_MAP = "图查";

    private ActivitySupplier4Binding binding;
    @Inject
    GoodsMapFragmentModel viewModel;
    private EnterprisePopWindow pickDistancePopWindow;
    public MapMarkerTools mapMarkerTools;
    private Marker markerLast;
    private int lastPosition = -1;
    private final List<PickSelectEntity> distanceData = new ArrayList<>();
    private MaterialAdapter promoteGoodsAdapter;
    private MaterialAdapter promoteGoodsAdapterBottom;
    private Double currentLat;
    private Double currentLong;
    private final List<GoodsListEntity> goods = new ArrayList<>();
    private final List<GoodsListEntity> goodsTemp = new ArrayList<>();
    private String distanceTemp = "";
    private String distance = "";
    private List<MenuEntity> data;
    private EnterprisePopWindowGoods demandHallTypePopWindow;
    private int testPosition;
    static final String[] PERMISSIONS = new String[]{Manifest.permission.READ_PHONE_STATE};
    private static final String SUCCESS = "SUCCESS";
    private boolean isLoadMoreGoodsList;
    private int mPageNum = 1;
    private final List<String> brandId = new ArrayList<>();
    private final List<String> mMaterValue = new ArrayList<>();
    private final List<String> mAreaId = new ArrayList<>();
    private boolean isZiYingChecked = false;
    private boolean isPromotionalChecked = false;
    private String goodsCid1 = "";
    private String name;
    private boolean isMarkerViewChecked = false;
    private boolean isFirstFail = true;
    private float downX = 0f;
    private float downY = 0f;
    private float moveX = 0f;
    private float moveY = 0f;
    private long currentMS = 0L;
    /**
     * 是否重置定位
     */
    private boolean isRePositioning = false;
    private TranslateAnimation mapCardAnimation;

    /**
     * @param isMap
     * @param data
     * @param fromWhere 0-地图查找  1-供应商
     * @return
     */
    public static NewGoodsMapFragment newInstance(boolean isMap, List<MenuEntity> data, String fromWhere) {
        NewGoodsMapFragment fragment = new NewGoodsMapFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean("isMap", isMap);
        bundle.putString("fromWhere", fromWhere);
        bundle.putSerializable("data", (Serializable) data);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerHomeFragComponent.builder()
                .appComponent(appComponent)
                .homeFragModule(new HomeFragModule(this))
                .build()
                .inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.activity_supplier4, container, false);
        initView(savedInstanceState);
        data = (List<MenuEntity>) getArguments().getSerializable("data");
        return binding.getRoot();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mapMarkerTools = new MapMarkerTools(getActivity(), getLifecycle());

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initAnimator();
        init();
    }

    private void initAnimator() {
        mapCardAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF,
                0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                1.0f);
        mapCardAnimation.setDuration(300);
    }

    /**
     *
     */
    private void initView() {
        SelectPopEntity selectPopEntity3 = new SelectPopEntity("距离", "5", false, true);
        SelectPopEntity selectPopEntity1 = new SelectPopEntity("自营", "1", false, false);
        SelectPopEntity selectPopEntity2 = new SelectPopEntity("促销", "2", false, false);
        binding.sct.addTextButton(selectPopEntity3);
        binding.sct.addTextButton(selectPopEntity1);
        binding.sct.addTextButton(selectPopEntity2);
        binding.sct.onSetCallPop((position, content, bg, entity) -> {
            testPosition = position;
            if ("5".equals(entity.getType())) {
                binding.sct.contentSelect(false, true, position);
                showDistancePopWindow();
            }
            if ("1".equals(entity.getType())) {
                isZiYingChecked = !isZiYingChecked;
                mapMarkerTools.mapClear();
                setMapCardInvisible();
                loadGoodsList(false);
            }
            if ("2".equals(entity.getType())) {
                isPromotionalChecked = !isPromotionalChecked;
                mapMarkerTools.mapClear();
                setMapCardInvisible();
                loadGoodsList(false);
            }
        });
        binding.setViewModel(viewModel);
        binding.tvLocation.setOnClickListener(this);
        binding.searchBtn.setOnClickListener(this);
        binding.ivMap.setOnClickListener(this);
        binding.editView.setOnClickListener(this);
        MenuEntity menuEntity = new MenuEntity();
        menuEntity.setName("全部");
        menuEntity.setId("");
        data.add(0, menuEntity);
        binding.etView.setHint("搜索商品");
        getDemanHallTabList(setSecondTypeDatas(data));
        binding.demandList.setPullRefreshEnabled(true);
        binding.demandList.setLoadingMoreEnabled(false);
        binding.demandList.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadGoodsList(false);
            }

            @Override
            public void onLoadMore() {

            }
        });

        binding.etView.setOnEditorActionListener((textView, i, keyEvent) -> {
            if (i == EditorInfo.IME_ACTION_SEARCH) {
                setMapCardInvisible();
                name = binding.etView.getText().toString().trim();
                loadGoodsList(false);
                return true;
            }
            return false;
        });
        initListener();
    }

    private void initListener() {
        SoftKeyBoardListener.setListener(requireActivity(), new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {//键盘处于打开状态
                binding.etView.setCursorVisible(true);// 显示光标
                isFilterViewVisibility(true);
            }

            @Override
            public void keyBoardHide(int height) {//键盘处于关闭状态
                binding.etView.setCursorVisible(false);// 隐藏光标
            }
        });
    }

    private void init() {
        demandHallTypePopWindow = new EnterprisePopWindowGoods(getActivity());
        demandHallTypePopWindow.setBgView(binding.grayLayout);
        demandHallTypePopWindow.setOnResultClick((key1, key2, key3) -> {
            binding.tabLayout.getTabAt((int) key3).select();
            if ("全部".equals(data.get((int) key3).getName() + "")) {
                goodsCid1 = "";
            } else {
                goodsCid1 = data.get((int) key3).getId();
            }
            loadGoodsList(false);
        });
        demandHallTypePopWindow.setOnDisMissClick(() -> binding.editView.setImageResource(R.drawable.btn_down));

        binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                setMapCardInvisible();
                setTabLayoutName(tab.getPosition());
                demandHallTypePopWindow.setDefData(tab.getPosition());
                if (tab.getCustomView() != null) {
                    TextView tabSelect = tab.getCustomView().findViewById(R.id.tv_tab_item_textview);
                    tabSelect.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                    tabSelect.setTextColor(getResources().getColor(R.color.APPTabColor));
                    tabSelect.invalidate();
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                if (tab != null && tab.getCustomView() != null) {
                    TextView tabSelect = tab.getCustomView().findViewById(R.id.tv_tab_item_textview);
                    tabSelect.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                    tabSelect.setTextColor(getResources().getColor(R.color.color_666666));
                    tabSelect.invalidate();
                }
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        pickDistancePopWindow = new EnterprisePopWindow(getActivity());
        pickDistancePopWindow.setBgView(binding.grayLayout);
        pickDistancePopWindow.setOnResultClick((key1, key2, key3) -> {
            distanceTemp = (String) key2;
            setMapCardInvisible();
            if ("不限".equals(distanceTemp)) {
                distance = "";
            } else {
                distance = ((String) key2).replace("KM", "");
            }
            loadGoodsList(false);
        });
        pickDistancePopWindow.setOnDisMissClick(() -> {
            binding.sct.contentSelect(null != distanceTemp && !"不限".equals(distanceTemp) && !"".equals(distanceTemp), false, testPosition);
        });

        if (binding.tvMap.getText().toString().equals(TYPE_MAP)) {
            binding.tvMap.setText(TYPE_MAP);
            binding.demandList.setVisibility(View.VISIBLE);
            binding.flMap.setVisibility(View.GONE);
            binding.mapView.setVisibility(View.GONE);
        } else {
            binding.tvMap.setText(TYPE_LIST);
            binding.demandList.setVisibility(View.GONE);
            binding.flMap.setVisibility(View.VISIBLE);
            binding.mapView.setVisibility(View.VISIBLE);
        }
        binding.tvLocation.setVisibility(View.VISIBLE);
        binding.vLine.setVisibility(View.VISIBLE);
    }

    private void loadGoodsList(boolean isLoadMore) {
        isLoadMoreGoodsList = isLoadMore;
        mPageNum = isLoadMore ? mPageNum + 1 : 1;
        if ("7".equals(goodsCid1)) {
            Map<String, Object> map = new HashMap<>();
            map.put("pageNum", mPageNum);
            map.put("pageSize", 20);
            map.put("distance", distance);
            map.put("distanceSort", "1");
            map.put("priceSort", "0");
            map.put("timeSort", "0");
            map.put("name", name);
            map.put("cid1", goodsCid1);
            map.put("categoryId", "");
            map.put("cid3", "");
            String mItemId = "";
            map.put("itemId", mItemId);
            map.put("brandId", brandId);
            map.put("materValue", mMaterValue);
            map.put("regionCode", mAreaId);
            map.put("areaId", "");
            map.put("areaCode", "");
            if (isZiYingChecked) {
                map.put("selfSupport", "1");
            }
            if (isPromotionalChecked) {
                map.put("promoteStatus", 2);
            }
            if (LocationUtil.isOpenLocation(getContext()) && LocationUtil.currentLocationIsValid()) {
                if (!isRePositioning) {
                    map.put("lon", String.valueOf(LocationUtil.getCurrentLongitude()));
                    map.put("lat", String.valueOf(LocationUtil.getCurrentLatitude()));
                } else {
                    map.put("lon", String.valueOf(currentLong));
                    map.put("lat", String.valueOf(currentLat));
                }
            } else {
                map.put("lon", "0");
                map.put("lat", "0");
            }
            mapMarkerTools.mapClear();
            viewModel.getConcreteList(map);
        } else {
            Map<String, Object> map = new HashMap<>();
            map.put("pageNum", mPageNum);
            map.put("pageSize", 20);
            map.put("distance", distance);
            map.put("distanceSort", "1");
            map.put("priceSort", "0");
            map.put("timeSort", "0");
            map.put("cid1", goodsCid1);
            map.put("name", name);
            map.put("categoryId", "");
            map.put("cid3", "");
            String mItemId = "";
            map.put("itemId", mItemId);
            map.put("brandId", brandId);
            map.put("materValue", StringUtil.formatListToString(mMaterValue));
            map.put("regionCode", mAreaId);
            map.put("areaId", "");
            map.put("areaCode", "");
            if (isZiYingChecked) {
                map.put("selfSupportTag", 1);
            }
            if (isPromotionalChecked) {
                map.put("promoteStatus", 2);
            }
            if (LocationUtil.isOpenLocation(getContext()) && LocationUtil.currentLocationIsValid()) {
                if (!isRePositioning) {
                    map.put("lon", String.valueOf(LocationUtil.getCurrentLongitude()));
                    map.put("lat", String.valueOf(LocationUtil.getCurrentLatitude()));
                } else {
                    map.put("lon", String.valueOf(currentLong));
                    map.put("lat", String.valueOf(currentLat));
                }
            } else {
                map.put("lon", "0");
                map.put("lat", "0");
            }
            viewModel.getGoodsList(map);
        }

    }

    private void resetMarker(String curMarkerId, Marker markerNew, int pos, String type) {
        if (null != markerLast) {
            BitmapDescriptor bitmapSmall;
            if ("1".equals(type)) {
                bitmapSmall = BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getActivity().getResources(), R.mipmap.wt_pub));
            } else {
                bitmapSmall = BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getActivity().getResources(), R.mipmap.wt_goods));
            }
            markerLast.setIcon(bitmapSmall);
        }

    }

    private void initView(Bundle savedInstanceState) {
        binding.demandList.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.goodsList.setLayoutManager(new LinearLayoutManager(getActivity()));
        promoteGoodsAdapter = new MaterialAdapter(getActivity(), null, false);
        promoteGoodsAdapterBottom = new MaterialAdapter(getActivity(), null, true);
        binding.demandList.swapAdapter(promoteGoodsAdapter, true);
        binding.goodsList.swapAdapter(promoteGoodsAdapterBottom, true);
        viewModel.getDistanceModel();
        MapView mMapView = binding.mapView;
        mMapView.getMap().setOnMapClickListener(latLng -> {
            if (isMarkerViewChecked) {
                isMarkerViewChecked = false;
            } else {
                if (binding.showList.getVisibility() == View.VISIBLE) {
                    setMapCardInvisible();
                }
            }
        });
        mMapView.getMap().setOnMapTouchListener(event -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    downX = event.getX();//float downX
                    downY = event.getY();//float DownY
                    moveX = 0;
                    moveY = 0;
                    currentMS = System.currentTimeMillis();//long currentMS     获取系统时间
                    break;
                case MotionEvent.ACTION_MOVE:
                    moveX += Math.abs(event.getX() - downX);//X轴距离
                    moveY += Math.abs(event.getY() - downY);//y轴距离
                    downX = event.getX();
                    downY = event.getY();
                    break;
                case MotionEvent.ACTION_UP:
                    long moveTime = System.currentTimeMillis() - currentMS;//移动时间
                    //判断是否继续传递信号
                    if (moveTime > 200 && (moveX > 20 || moveY > 20)) {
                        isFilterViewVisibility(false);
                        //不再执行后面的事件，在这句前可写要执行的触摸相关代码。点击事件是发生在触摸弹起后
                    }
                    break;
                default:
                    break;
            }
        });

        mapMarkerTools.init(savedInstanceState, mMapView);
        mapMarkerTools.setMarkerClick(new MapMarkerTools.MarkerClick() {
            @Override
            public void onMarkerClick(int pos, String title) {

            }

            @Override
            public void onMarkerClick(int pos, String title, Marker marker) {
                isMarkerViewChecked = true;
                showGoodsMarkerView(pos, title);
                BitmapDescriptor bitmapSmall = BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getActivity().getResources(), R.mipmap.wt_goods_big));
                marker.setIcon(bitmapSmall);
                if (lastPosition == Integer.parseInt(title)) {
                    return;
                }
                resetMarker(marker.getId(), marker, pos, "2");
                markerLast = marker;
                lastPosition = Integer.parseInt(title);
                mapMarkerTools.jumpPoint(marker);
            }

            @Override
            public void onLocationChanged(Double Lat, Double Log, String address) {
                if (currentLat == null || currentLat <= 0) {
                    currentLat = Lat;
                    currentLong = Log;
                    loadGoodsList(false);
                    cameraToPosition();
                }
            }

            @Override
            public void getAddress(Double Lat, Double Log, String address) {

            }

            @Override
            public void failure() {
                //未开启定位权限，该回调会重复调用
                if (isFirstFail) {
                    loadGoodsList(false);
                }
                isFirstFail = false;
            }
        });

        promoteGoodsAdapter.setOnItemClick(new AdapterOnItemClick<GoodsListEntity>() {
            @Override
            public void onItemClick(GoodsListEntity entity, int position) {
                if (entity.isST()) {
                    MaterialFilterJson filterJson = new MaterialFilterJson();
                    filterJson.setStrengthId(entity.getSort());
                    ConcreteDetailActivity2.start(getActivity(), entity.getId(), filterJson);
                } else {
                    ShopGoodsDetailActivity.start(getActivity(), entity.getId(), "", entity.getSkuid());
                }
            }
        });

        promoteGoodsAdapterBottom.setOnItemClick(new AdapterOnItemClick<GoodsListEntity>() {
            @Override
            public void onItemClick(GoodsListEntity entity, int position) {
                if (entity.isST()) {
                    MaterialFilterJson filterJson = new MaterialFilterJson();
                    filterJson.setStrengthId(entity.getSort());
                    ConcreteDetailActivity2.start(getActivity(), entity.getId(), filterJson);
                } else {
                    ShopGoodsDetailActivity.start(getActivity(), entity.getId(), "", entity.getSkuid());
                }
            }
        });

        promoteGoodsAdapterBottom.setCallBack((type, entity) -> {
            switch (type) {
                case 1://交流
                    if (!UserOperating.getInstance().isLogged()) {
                        VerificationCodeLoginActivity.start(getActivity(), EventConstant.EVENT_SHOP_GOODS_DETAIL_ACTIVITY_JUMP);
                    } else {
                        if (entity.isST()) {
                            viewModel.getGoodsImAccount(entity.getId(), 2);
                        } else {
                            viewModel.getGoodsImAccount(entity.getId(), 1);
                        }
                    }
                    break;
                case 2://询价
                    inquiryPublish(entity);
                    break;
                case 3://加入购物车
                    certification(1, entity);
                    break;
                case 4://采购
                    certification(2, entity);
                    break;
                default:
                    break;
            }
        });
    }

    private void isFilterViewVisibility(boolean isVisibility) {
        if (isVisibility) {
            if (binding.filterContainer.getVisibility() == View.GONE) {
                binding.filterContainer.setVisibility(View.VISIBLE);
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) binding.llGoodsTag.getLayoutParams();
                layoutParams.topMargin = ResolutionUtil.dp2px(getActivity(), 90);
                binding.llGoodsTag.setLayoutParams(layoutParams);
            }
        } else {
            if (binding.filterContainer.getVisibility() == View.VISIBLE) {
                binding.filterContainer.setVisibility(View.GONE);
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) binding.llGoodsTag.getLayoutParams();
                layoutParams.topMargin = ResolutionUtil.dp2px(getActivity(), 40);
                binding.llGoodsTag.setLayoutParams(layoutParams);
            }
        }
    }

    private void setMapCardInvisible() {
        if (mapCardAnimation != null && binding.showList.getVisibility() == View.VISIBLE) {
            binding.showList.startAnimation(mapCardAnimation);
            binding.showList.setVisibility(View.GONE);
            resetMarker("", null, 0, "2");
        }
    }

    public void showWebsiteInfo(WebsiteInfoEntity entity, String websiteNo, int type) {
        viewModel.getPermissionMenu(entity, 1, websiteNo, entity.getName(), type);
    }

    public void getPermission(WebsiteInfoEntity entity, int websiteType, String
            websiteNo, String companyName, int type) {
        if (type == 1) {
            QualityMemberBean bean = new QualityMemberBean();
            bean.setCompanyNo(websiteNo);
            bean.setCompanyName(companyName);
            MemberApplyJoinActivity.start(getActivity(), bean);

        } else {
            QualityMemberBean bean1 = new QualityMemberBean();
            bean1.setCompanyNo(websiteNo);
            bean1.setCompanyName(entity.getName());
            bean1.setServiceTypeName(entity.getServiceTypeName());
            bean1.setServiceType(entity.getServiceType());
            MemberInviteJoinActivity.start(getActivity(), bean1);
        }
    }

    /**
     * 未登录弹框跳转认证
     */
    public void showLogInDialog() {
        View view = View.inflate(getActivity(), R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        TextView tv_title = view.findViewById(R.id.tv_title);
        TextView tv_message = view.findViewById(R.id.tv_message);
        tv_title.setVisibility(View.VISIBLE);
        tv_title.setText("温馨提示");
        TextView tv_logout_confirm = view.findViewById(R.id.tv_logout_confirm);
        tv_logout_confirm.setText("确定");
        TextView tv_logout_cancel = view.findViewById(R.id.tv_logout_cancel);
        tv_message.setText("未登录，请先登录。");
        tv_logout_confirm.setOnClickListener(v -> {
            VerificationCodeLoginActivity.start(getActivity(), EventConstant.EVENT_MAIN_ACTIVITY_JUMP);
            roundCornerDialog.dismiss();
        });
        tv_logout_cancel.setOnClickListener(v -> roundCornerDialog.dismiss());
    }


    private void checkAddTokenView(GoodsListEntity entity, boolean isPurchase) {
        ShoppingCarRequest addShoppingCar = new ShoppingCarRequest();
        addShoppingCar.setItemId(entity.getId());
        if (!TextUtils.isEmpty(entity.getSkuid())) {
            addShoppingCar.setSkuId(entity.getSkuid());
        }
        addShoppingCar.setItemNum(TextUtils.isEmpty(entity.getLowestBuy()) ? "1" : entity.getLowestBuy());
        addShoppingCar.setChoosePriceType(entity.getPriceType());
        viewModel.addShoppingCar(addShoppingCar, isPurchase);
    }

    /***
     * 获取采购单列表数据
     * 根据skuId判断当前商品中是否包含在采购单中
     * 如果包含则跳转值核对订单页面
     * @param data
     */
    public void showShoppingCarDetail(List<ShoppingCarResponse> data, String skuId) {
        if (data == null || data.size() == 0) {
            MToast.showToast(getActivity(), "采购单里没有商品，请先将商品加入采购单");
            return;
        }
        List<ShoppingCarResponse> shoppingCarResponseList = new ArrayList<>();
        boolean isExistItem = false;
        for (ShoppingCarResponse response : data) {
            List<ShoppingCarResponse.ItemsData> itemsData = response.getItems();
            ShoppingCarResponse shoppingCarResponse = new ShoppingCarResponse();
            List<ShoppingCarResponse.ItemsData> itemsData0 = new ArrayList<>();
            if (itemsData != null && itemsData.size() > 0) {
                for (ShoppingCarResponse.ItemsData itemsData1 : itemsData) {
                    if (itemsData1.getSkuId().equals(skuId) && itemsData1.getItemStatus() == 1) {
                        isExistItem = true;
                        itemsData0.add(itemsData1);
                    }

                }
            }
            if (itemsData0.size() > 0) {
                shoppingCarResponse.setPayState(response.getPayState());
                shoppingCarResponse.setImAccount(response.getImAccount());
                shoppingCarResponse.setCompanyNo(response.getCompanyNo());
                shoppingCarResponse.setCompanyName(response.getCompanyName());
                shoppingCarResponse.setCompanyId(response.getCompanyId());
                shoppingCarResponse.setIsOpenAccount(response.getIsOpenAccount());
                shoppingCarResponse.setSelfSupportTag(response.getSelfSupportTag());
                shoppingCarResponse.setItems(itemsData0);
                shoppingCarResponseList.add(shoppingCarResponse);
            }
        }
        if (isExistItem) {
            Intent intent = new Intent(getActivity(), StatementActivity.class);
            intent.putExtra("PURCHASE_ORDER", (Serializable) shoppingCarResponseList);
            startActivity(intent);
        } else {
            MToast.showToast(getActivity(), "请先将商品加入采购单再采购");
        }
    }

    private void certification(int typeName, GoodsListEntity entity) {
        if (!UserOperating.getInstance().isLogged()) {
            jumpLogin(typeName, entity);
        } else {
            certificationI(typeName, entity);
        }
    }

    /***
     * 提示弹窗
     * @param
     * @param
     */
    private void showDialog() {
        View view = View.inflate(getActivity(), R.layout.dialog_one_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);
        TextView tv_title = view.findViewById(R.id.tv_title);
        TextView tv_message = view.findViewById(R.id.tv_message);
        tv_title.setVisibility(View.GONE);
        tv_message.setText("当前暂不支持个人用户下单，请切换\n到企业身份后再试");
        TextView tv_logout_confirm = view.findViewById(R.id.tv_logout_confirm);
        tv_logout_confirm.setText("知道了");
        tv_logout_confirm.setTextColor(getActivity().getResources().getColor(R.color.color_5792FD));
        tv_message.setTextColor(getActivity().getResources().getColor(R.color.color_666666));
        tv_message.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        tv_logout_confirm.setOnClickListener(v -> roundCornerDialog.dismiss());
    }

    /***
     * 团队加入企业-提示弹窗
     * @param
     */
    private void showJoinDialog() {
        View view = View.inflate(getActivity(), R.layout.dialog_two_button_vertical, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);
        TextView tv_title = view.findViewById(R.id.tv_title);
        TextView tv_message = view.findViewById(R.id.tv_message);
        TextView tv_join = view.findViewById(R.id.tv_join);
        tv_title.setVisibility(View.GONE);
        tv_message.setText("您没有权限，请加入认证\n企业后再试");
        TextView tv_logout_confirm = view.findViewById(R.id.tv_logout_confirm);
        tv_logout_confirm.setText("知道了");
        tv_message.setTextColor(getActivity().getResources().getColor(R.color.color_666666));
        tv_message.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        tv_join.setOnClickListener(v -> {
            JoinCompanyActivity.start(getActivity());
            roundCornerDialog.dismiss();
        });
        tv_logout_confirm.setOnClickListener(v -> roundCornerDialog.dismiss());
    }

    /***
     * 团队加入企业-提示弹窗
     * @param
     */
    private void showJoin2Dialog() {
        View view = View.inflate(getActivity(), R.layout.dialog_map_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);
        TextView tv_message = view.findViewById(R.id.tv_message);
        TextView tvCancel = view.findViewById(R.id.tv_cancel);
        TextView tvConfirm = view.findViewById(R.id.tv_confirm);
        tv_message.setText("请将身份切换到企业或者加入\n已认证的企业后再试");
        tvConfirm.setOnClickListener(v -> {
            JoinCompanyActivity.start(getActivity());
            roundCornerDialog.dismiss();
        });
        tvCancel.setOnClickListener(v -> roundCornerDialog.dismiss());
    }

    private void inquiryPublish(GoodsListEntity entity) {
        if (authentication()) {
            if (entity.isST()) {
                buildInquiryConcreteParam(entity);
            } else {
                buildInquiryGoodsParam(entity);
            }
        }
    }

    /**
     * 构建商砼参数
     *
     * @param entity
     */
    private void buildInquiryConcreteParam(GoodsListEntity entity) {
        viewModel.getConcreteDetail(entity.getId());
    }

    /**
     * 构建商品参数
     *
     * @param entity
     */
    private void buildInquiryGoodsParam(GoodsListEntity entity) {
        viewModel.getGoodsItemInformationById(entity.getId(), entity.getSkuid(), entity.getShopId());
    }

    public void setGoodsItemInformation(GoodsPublishEntity entity, String id, String
            skuId, String shopId) {
        if (entity != null) {
            viewModel.getDetailModel(id, skuId, shopId, entity);
        }
    }

    /**
     * * 构建商品信息(由于数据是多个接口数据的拼接。数据可能出错)
     *
     * @param skuDetailEntity
     * @param goodsPublishEntity
     */
    public void buildGoodsItemParam(GoodsSkuDetailEntity skuDetailEntity, GoodsPublishEntity
            goodsPublishEntity, String shopId) {
        viewModel.getCompanyInformation(skuDetailEntity, goodsPublishEntity, shopId);
    }

    public void buildCheckParam(GoodsSkuDetailEntity skuDetailEntity, GoodsPublishEntity
            goodsPublishEntity, CompanyDetailsEntity companyDetailsEntity) {
        InquiryDetailsEntity enquiryDetailsEntity = new InquiryDetailsEntity();
        List<GoodsItemEntity> goodsItems = new ArrayList<>();
        if (goodsPublishEntity != null) {
            GoodsItemEntity goodsItem = new GoodsItemEntity();
            goodsItem.setBrandId(goodsPublishEntity.getBrandId());
            goodsItem.setBrandName(goodsPublishEntity.getBrandName());
            goodsItem.setFcategory(goodsPublishEntity.getCid1());
            goodsItem.setFcatName(goodsPublishEntity.getCid1Name());
            goodsItem.setNum((TextUtils.isEmpty(goodsPublishEntity.getLowestBuy()) || "0".equals(goodsPublishEntity.getLowestBuy()) ? "1" : goodsPublishEntity.getLowestBuy()));
            goodsItem.setScategory(goodsPublishEntity.getCid2());
            goodsItem.setScatName(goodsPublishEntity.getCid2Name());
            goodsItem.setSort("1");
            goodsItem.setTcategory(goodsPublishEntity.getCid3());
            goodsItem.setTcatName(goodsPublishEntity.getCid3Name());
            goodsItem.setUnit(goodsPublishEntity.getUnit());

            if (skuDetailEntity.getItemAttr() != null && skuDetailEntity.getItemAttr().getSku() != null && skuDetailEntity.getItemAttr().getSku().size() != 0) {
                List<GoodsAttrEntity> attrList = new ArrayList<>();
                for (SkuItemAttrEntity attrChildEntity : skuDetailEntity.getItemAttr().getSku()) {

                    if (attrChildEntity != null && attrChildEntity.getList() != null && attrChildEntity.getList().size() != 0) {
                        for (SkuItemAttrEntity.Child child : attrChildEntity.getList()) {
                            GoodsAttrEntity attr = new GoodsAttrEntity();
                            if (child.isChecked()) {
                                attr.setParamValId(child.getValId());
                                attr.setParamValName(child.getValData());
                                attr.setParamId(attrChildEntity.getId());
                                attr.setParamName(attrChildEntity.getParamData());
                                attrList.add(attr);
                            }
                        }
                    }
                }
                goodsItem.setAttrList(attrList);
            }
            goodsItems.add(goodsItem);
        }
        enquiryDetailsEntity.setItemList(goodsItems);

        List<InquiryDetailsEntity.InviteCompanyList> inviteCompanyList = new ArrayList<>();
        InquiryDetailsEntity.InviteCompanyList companyListDTO = new InquiryDetailsEntity.InviteCompanyList();
        companyListDTO.setSupplierName(companyDetailsEntity.getCompanyName());
        companyListDTO.setSupplier(companyDetailsEntity.getCompanyNo());
        companyListDTO.setProvinceName(companyDetailsEntity.getProvinceName());
        companyListDTO.setProvinceNo(companyDetailsEntity.getProvinceNo());
        inviteCompanyList.add(companyListDTO);
        enquiryDetailsEntity.setInviteCompanyList(inviteCompanyList);
        ARouter.getInstance().build(Constants.ARouter.AR_INQUIRY_PUBLISHING)
                .withSerializable(InquiryPublishingActivity.KEY_GOODS_DETAIL, enquiryDetailsEntity)
                .navigation();
    }

    private boolean authentication() {
        //跳转到询价页面前需用户认证
        if (!UserOperating.getInstance().isLogged()) {
            VerificationCodeLoginActivity.start(getActivity(), EventConstant.EVENT_SHOP_GOODS_DETAIL_ACTIVITY_JUMP);
            return false;
        }
        int type = UserOperating.getInstance().getUserIdentity();
        if (type == 0) {
            if (!SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false)) {
                //个人未实名认证--实名认证或加入企业
                new ThreeButtonDialog.Builder(getActivity())
                        .title("温馨提示")
                        .content("您没有权限，请认证或加入企业后再试")
                        .confirmCallback(v -> {
                            //实名认证
                            AuthActivity3.start(getActivity());
                        }).joinCallback(v -> {
                    //去加入企业
                    JoinCompanyActivity.start(getActivity());
                }).show();
                return false;
            }

        } else if (type == 1) {
            int type1 = ACAdminDialogUtils.isPermissionForAsk(MK_OURINQUIRYPRICELIST, false);
            if (type1 != ACAdminDialogUtils.TYPE_NORMAL /*&& !SUCCESS.equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.ENTERPRISE_AUTH, ""))*/) {
                MToast.showToast(getActivity(), "您没有权限，请联系管理员开通");
                return false;
            }
        } else if (type == 2) {
            showJoin2Dialog();
            return false;
        }
        return true;
    }

    private boolean existSdCard() {
        if (android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    private void jumpLogin(int typeName, GoodsListEntity entity) {
        if (!existSdCard()) {
            VerificationCodeLoginActivity.start(getActivity(), EventConstant.EVENT_SHOP_GOODS_DETAIL_ACTIVITY_JUMP);
        } else {
            boolean shanyan = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.ShanYan, false);
            if (shanyan) {
                //校验权限
                //申请动态权限
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    //6.0以上运行时权限处理
                    EsayPermissions.with(getActivity()).constantRequest().permission(PERMISSIONS).request(new OnPermission() {
                        @Override
                        public void hasPermission(List<String> granted, boolean isAll) {
                            openLoginPage(typeName, entity);
                        }

                        @Override
                        public void noPermission(List<String> denied, boolean quick) {
                            openLoginPage(typeName, entity);
                        }
                    });

                } else {
                    //有权限
                    openLoginPage(typeName, entity);
                }

            } else {
                VerificationCodeLoginActivity.start(getActivity(), EventConstant.EVENT_SHOP_GOODS_DETAIL_ACTIVITY_JUMP);
            }
        }
    }

    /**
     * 拉起授权页
     */
    private void openLoginPage(int type, GoodsListEntity entity) {
        //设置授权页样式
        OneKeyLoginManager.getInstance().setAuthThemeConfig(ConfigUtils.getCJSConfig(getActivity()));
        //开始拉取授权页
        DialogHelper.showProgressDialog2(getActivity(), null, "数据加载中", 0, true, null, true);
        OneKeyLoginManager.getInstance().openLoginAuth(false, new OpenLoginAuthListener() {
            @Override
            public void getOpenLoginAuthStatus(int code, String result) {
                DialogHelper.dismissProgressDialog();
            }
        }, (code, result) -> {
            DialogHelper.dismissProgressDialog();
            if (code == 1000) {
                OneKeyLoginEntity oneKeyLoginEntity = GsonManager.getInstance().getGson().fromJson(result, OneKeyLoginEntity.class);
                oneKeyLoginEntity.setPlateform("Android");
                viewModel.oneKeyLogin(oneKeyLoginEntity, type, entity);
            }
        });
    }

    public void oneKeyLoginSuccess(int typeName, GoodsListEntity entity) {
        certificationI(typeName, entity);
    }

    private void certificationI(int typeName, GoodsListEntity entity) {
        int type = UserOperating.getInstance().getUserIdentity();
        if (type == 0) {
            if (SUCCESS.equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.ENTERPRISE_AUTH, ""))) {
                showDialog();
            } else {
                new ThreeButtonDialog.Builder(getActivity())
                        .content("当前暂不支持个人用户下单，加入企\n业/认证企业后可下单")
                        .confirm("认证企业")
                        .cancel("知道了")
                        .confirmCallback(v -> {
                            RegisterActivity3.start(getActivity(), true);
                        }).joinCallback(v -> {
                    JoinCompanyActivity.start(getActivity());
                }).show();
            }
            return;

        } else if (type == 1) {
            int type1 = ACAdminDialogUtils.isPermissionForAsk(MK_OURINQUIRYPRICELIST, false);
            if (type1 != ACAdminDialogUtils.TYPE_NORMAL /*&& !SUCCESS.equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.ENTERPRISE_AUTH, ""))*/) {
                MToast.showToast(getActivity(), "您没有权限，请联系管理员开通");
                return;
            }
        } else if (type == 2) {
            showJoinDialog();
            return;
        }
        switch (typeName) {
            case 1:
                checkAddTokenView(entity, false);
                break;
            case 2:
                checkAddTokenView(entity, true);
                break;
            default:
                break;
        }
    }

    /**
     * 获取tab页签名称
     *
     * @param position
     */
    private void setTabLayoutName(int position) {
        if (null != data && data.size() > 0) {
            if ("全部".equals(data.get(position).getName() + "")) {
                goodsCid1 = "";
            } else {
                goodsCid1 = data.get(position).getId();
            }
            loadGoodsList(false);
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_close:
                binding.showList.setVisibility(View.GONE);
                break;
            case R.id.iv_back:
                getActivity().finish();
                break;
            case R.id.tv_location:
                if (binding.showList.getVisibility() == View.VISIBLE) {
                    setMapCardInvisible();
                }
                Intent intent = new Intent();
                intent.setClass(getActivity(), SelectAddressActivity.class);
                intent.putExtra(SelectAddressActivity.TITLE, "选择区域");
                intent.putExtra(SelectAddressActivity.SHOW_DELETE, "SHOW_DELETE");
                intent.putExtra(SelectAddressActivity.LATITUDE, currentLat);
                intent.putExtra(SelectAddressActivity.LONGTITUDE, currentLong);
                startActivityForResult(intent, 101);
                break;
            case R.id.edit_view://材料类型下拉框
                if (null == data || data.size() == 0) {
                    return;
                }
                binding.editView.setImageResource(R.drawable.btn_shop_up);
                demandHallTypePopWindow.showPopwindow(binding.viewLine, 0, 0);
                demandHallTypePopWindow.setData(setSecondTypeDatas(data));
                break;
            case R.id.iv_map:
                if (binding.tvMap.getText().toString().equals(TYPE_MAP)) {
                    binding.tvMap.setText(TYPE_LIST);
                    binding.ivMap.setImageDrawable(ContextCompat.getDrawable(getActivity(), R.mipmap.icon_search_map));
                    binding.demandList.setVisibility(View.GONE);
                    binding.flMap.setVisibility(View.VISIBLE);
                    binding.mapView.setVisibility(View.VISIBLE);
                } else {
                    binding.tvMap.setText(TYPE_MAP);
                    binding.ivMap.setImageDrawable(ContextCompat.getDrawable(getActivity(), R.mipmap.icon_search_list));
                    RecyclerView.Adapter listAdapter = binding.demandList.getAdapter();
                    if (listAdapter != null && listAdapter.getItemCount() > 0) {
                        binding.demandList.setVisibility(View.VISIBLE);
                        binding.emptyView.setVisibility(View.GONE);
                    } else {
                        binding.emptyView.setVisibility(View.VISIBLE);
                    }
                    binding.flMap.setVisibility(View.GONE);
                    binding.mapView.setVisibility(View.GONE);
                }
                binding.tvLocation.setVisibility(View.VISIBLE);
                binding.vLine.setVisibility(View.VISIBLE);
                break;

            case R.id.search_btn:
                setMapCardInvisible();
                name = binding.etView.getText().toString().trim();
                loadGoodsList(false);
                break;
            default:
                break;
        }
    }

    private List<PickSelectEntity> setSecondTypeDatas(List<MenuEntity> data) {
        List<PickSelectEntity> types = new ArrayList<>();
        if (data != null) {
            for (MenuEntity entity : data) {
                PickSelectEntity dictEntity3 = new PickSelectEntity();
                dictEntity3.setNo(entity.getId());
                dictEntity3.setProjectscale(entity.getName());
                types.add(dictEntity3);
            }
        }
        return types;
    }

    public void getDemanHallTabList(List<PickSelectEntity> data) {
        if (null != data && data.size() > 0) {
            for (int i = 0; i < data.size(); i++) {
                binding.tabLayout.addTab(binding.tabLayout.newTab());
                binding.tabLayout.getTabAt(i).setCustomView(R.layout.tab_item_textview);
                TextView tv = binding.tabLayout.getTabAt(i).getCustomView().findViewById(R.id.tv_tab_item_textview);
                tv.setText(data.get(i).getProjectscale());
                if (i == 0) {
                    tv.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                    tv.setTextColor(getResources().getColor(R.color.APPTabColor));
                }
            }
        } else {
            MToast.showToast(getActivity(), "数据未加载");
        }
    }

    private void showDistancePopWindow() {
        pickDistancePopWindow.showPopwindowGoods(binding.sct);
        pickDistancePopWindow.setData(distanceData);
    }


    public void showDistancePopWindow(List<DictEntity3> data) {
        setSecondDistanceData(data);
        pickDistancePopWindow.setData(distanceData);
    }

    private void setSecondDistanceData(List<DictEntity3> data) {
        List<PickSelectEntity> types = new ArrayList<>();
        if (data != null) {
            for (DictEntity3 entity : data) {
                PickSelectEntity pickSelectEntity = new PickSelectEntity();
                pickSelectEntity.setNo(entity.getId());
                pickSelectEntity.setProjectscale(entity.getName());
                types.add(pickSelectEntity);
            }
        }
        distanceData.clear();
        PickSelectEntity entityTemp = new PickSelectEntity();
        entityTemp.setNo("10000000");
        entityTemp.setProjectscale("不限");
        distanceData.addAll(types);
        distanceData.add(0, entityTemp);
    }

    public void showGoodsList(List<GoodsListEntity> data) {
        if (isLoadMoreGoodsList) {
            binding.demandList.loadMoreComplete();
            if (data.size() != 0) {
                promoteGoodsAdapter.addDatas(data);
            }
        } else {
            binding.demandList.setAdapter(promoteGoodsAdapter);
            binding.demandList.refreshComplete();
            if (data.size() == 0) {
                binding.emptyView.setVisibility(View.VISIBLE);
                binding.demandList.setLoadingMoreEnabled(false);
                binding.demandList.setVisibility(View.GONE);
            } else {
                binding.demandList.setVisibility(View.VISIBLE);
                binding.emptyView.setVisibility(View.GONE);
                binding.demandList.setLoadingMoreEnabled(false);
                binding.demandList.loadMoreComplete();
            }
            promoteGoodsAdapter.setDatas(data);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && data != null) {
            currentLat = data.getDoubleExtra(SelectAddressActivity.LATITUDE, 0);
            currentLong = data.getDoubleExtra(SelectAddressActivity.LONGTITUDE, 0);
            isRePositioning = true;
            loadGoodsList(false);
            cameraToPosition();
        }
    }

    //设置定位点
    private void cameraToPosition() {
        mapMarkerTools.setMyLocation(currentLat, currentLong);
    }

    public void addGoodsMarkInfoWindow(List<GoodsListEntity> data) {
        try {
            goods.clear();
            goodsTemp.clear();
            if (data.size() == 0) {
                mapMarkerTools.mapClear();
                return;
            }
            if (!isLoadMoreGoodsList) {
                mapMarkerTools.mapClear();
            }
            goods.addAll(data);
            goodsTemp.addAll(data);
            ListIterator<GoodsListEntity> listIterator = goodsTemp.listIterator();
            while (listIterator.hasNext()) {
                GoodsListEntity next = listIterator.next();
                for (GoodsListEntity entity : goodsTemp) {
                    if (entity.getLatitude().equals(next.getLatitude()) && entity.getLongitude().equals(next.getLatitude())) {
                        listIterator.remove();
                    }
                }
            }

            for (int i = 0; i < goodsTemp.size(); i++) {
                GoodsListEntity entity = goodsTemp.get(i);
                if (null != entity && !TextUtils.isEmpty(entity.getLatitude()) && !TextUtils.isEmpty(entity.getLongitude())) {
                    double currentLat = Double.parseDouble(entity.getLatitude());
                    double currentLong = Double.parseDouble(entity.getLongitude());
                    if (currentLat == 0 || currentLong == 0) {
                        continue;
                    }
                    mapMarkerTools.addPoiItem(currentLat, currentLong, "");
                }
            }
            mapMarkerTools.addAllMarkerToMap(R.mipmap.wt_goods, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showGoodsMarkerView(int pos, String title) {
        GoodsListEntity entity = goodsTemp.get(Integer.parseInt(title));
        List<GoodsListEntity> tempList = new ArrayList<>();
        for (int i = 0; i < goods.size(); i++) {
            String tempLatitude = goods.get(i).getLatitude();
            String tempLongitude = goods.get(i).getLongitude();
            if (entity.getLatitude().equals(tempLatitude) && entity.getLongitude().equals(tempLongitude)) {
                tempList.add(goods.get(i));
            }
        }
        binding.showList.setVisibility(View.VISIBLE);
        binding.goodsList.setAdapter(promoteGoodsAdapterBottom);
        promoteGoodsAdapterBottom.setDatas(tempList);
    }

    public void showConcreteCompanyDetail(CompanyDetailsEntity entity, String cartTitle) {
        ConcreteEntity concrete = new ConcreteEntity();
        concrete.setFcategory("7");
        concrete.setFcatName("商砼");
        concrete.setScategory("14");
        concrete.setScatName("商品混凝土");
        concrete.setSort("2");
        concrete.setTcategory("15");
        concrete.setTcatName("商品混凝土");
        concrete.setUnit("立方米");

        List<InquiryDetailsEntity.InviteCompanyList> companyListDTOS = new ArrayList<>();
        InquiryDetailsEntity.InviteCompanyList inviteCompanyListDTO = new InquiryDetailsEntity.InviteCompanyList();
        inviteCompanyListDTO.setSupplier(entity.getCompanyNo());
        inviteCompanyListDTO.setSupplierName(entity.getCompanyName());
        inviteCompanyListDTO.setProvinceNo(entity.getProvinceNo());
        inviteCompanyListDTO.setProvinceName(entity.getProvinceName());
        companyListDTOS.add(inviteCompanyListDTO);
        DatalUtils.getInstance().putData(MkvUtils.CacheModular, CacheMarker.CacheGoodsSupplierModel, companyListDTOS);

        Intent createGood = new Intent(getActivity(), NewPurchasesActivity.class);
        createGood.putExtra("GOOD_EDIT", false);
        createGood.putExtra("GOOD_ADD", false);
        createGood.putExtra("GOOD_ENTITY", concrete);
        startActivity(createGood);
    }


    public void showImWindow(List<EnquiryImAlternateEntity.CompanyCustomersDTO> companyCustomers) {
        if (companyCustomers.size() == 1) {
            if (companyCustomers.get(0) != null && !TextUtils.isEmpty(String.valueOf(companyCustomers.get(0).getImAccount()))) {
                IMUtils.getInstance().buildSingleTalking(String.valueOf(companyCustomers.get(0).getImAccount()));
            }
        } else {
            List<CallPhoneEntity> datas = new ArrayList<>();
            for (int i = 0; i < companyCustomers.size(); i++) {
                CallPhoneEntity entity = new CallPhoneEntity();
                entity.setType("1");
                entity.setPrincipalName(companyCustomers.get(i).getPrincipalName());
                entity.setImAccount(companyCustomers.get(i).getImAccount());
                entity.setImToken(companyCustomers.get(i).getImToken());
                datas.add(entity);
            }
            CallPhonePopWindow window = new CallPhonePopWindow(getActivity());
            window.setBgView(binding.grayLayout);
            window.setData(datas);
            if (!window.isShowing()) {
                window.showDownPopwindow(binding.grayLayout, true);
            }
        }
    }
}
